package com.jframe.sys.orm.jdbc;

import java.util.*;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.jframe.app.model.DataSourse;
import com.jframe.app.service.DataSourseService;
import com.jframe.sys.utils.SpringUtil;
import com.jframe.sys.utils.StringUtil;

/**
 * 管理类DBPool支持对一个或多个系统中定义的数据库连接
 * 池的访问.客户程序可以调用getInstance()方法访问本类的唯一实例.
 */ 
public class DBPool {
	private static Map<String,DruidDataSource> poolMap=null;
	 
	    private static class DruidPoolHolder {
	        public static DBPool dbPool = new DBPool();
	    }
	    
	    static {
	    	DataSourseService dataSourseService = (DataSourseService)SpringUtil.getBean("dataSourseService");
			List<DataSourse> dataSourses = dataSourseService.findAll();
			poolMap = new HashMap<String,DruidDataSource>();
			for(DataSourse dataSource:dataSourses){
		        Properties properties = new Properties();
		        properties.setProperty("username", dataSource.getUser());
		        properties.setProperty("password", StringUtil.decrypt(dataSource.getPwd()));
		        properties.setProperty("driverClassName", dataSource.getDriver());
		        properties.setProperty("url", dataSource.getLinkStr());
		        properties.setProperty("minIdle", ""+dataSource.getMinIdle());
		        properties.setProperty("initialSize",""+dataSource.getInitialNum());
		        properties.setProperty("maxActive", ""+dataSource.getMaxActive());
		        properties.setProperty("filters", "stat");
		        properties.setProperty("maxWait","60000");
		        properties.setProperty("timeBetweenEvictionRunsMillis", "60000");
		        properties.setProperty("minEvictableIdleTimeMillis", "300000");
		        properties.setProperty("testWhileIdle","true");
		        properties.setProperty("testOnBorrow","false");
		        properties.setProperty("testOnReturn","false");
		        properties.setProperty("poolPreparedStatements","true");
		        properties.setProperty("maxPoolPreparedStatementPerConnectionSize","20");
	        	try {
					poolMap.put(dataSource.getConName(), (DruidDataSource) DruidDataSourceFactory
					        .createDataSource(properties));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		       
			}
	    }
	    
	    private DBPool() {}  //singleton
	     
	    /**
	     * 得到一个数据库连接池实例
	     * @return DBPool 实例
	     */
	    public static DBPool getInstance() {
	        return DruidPoolHolder.dbPool;
	    }
	     
	    /**
	     * 得到一个连接
	     * @return DruidPooledConnection 一个连接
	     *
	     */
	    public DruidDataSource getDruidDataSource(String dbKey){	    	
	        return poolMap.get(dbKey);
	    }
	     
}
